package com.personal.system.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.personal.common.result.Result;
import com.personal.system.config.MinioConfig;
import com.personal.system.domain.MinioFile;
import com.personal.system.domain.MinioResponseDTO;
import com.personal.system.mapper.sys.MinioFileMapper;
import com.personal.system.utils.MinioClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/file")
@Slf4j
@Api(tags = "文件上传管理")
@AllArgsConstructor
public class FileHandleController {

    private MinioClientUtils minioClientUtils;

    private MinioConfig minioConfig;

    private MinioFileMapper minioFileMapper;

    @PostMapping(value = {"/uploadFile"})
    @ApiOperation(value = "上传文件,支持批量上传")
    @ApiImplicitParam(name = "files",value = "文件对象",dataType = "File")
    public Result uploadFile(@RequestParam("file") List<MultipartFile> files) {
        log.info(files.toString());
        if (CollUtil.isEmpty(files)){
            return Result.fail("未选择文件！");
        }

        List<MinioResponseDTO> responseDTOList=new ArrayList<>();
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
//            获取文件拓展名
            String extName = FileUtil.extName(originalFilename);
            log.info("文件拓展名:"+extName);
//            生成新的文件名，存入到minio
            long millSeconds = Instant.now().toEpochMilli();
            String minioFileName=millSeconds + RandomStringUtils.randomNumeric(12)+"."+extName;
            String contentType = file.getContentType();
            log.info("文件mime:{}",contentType);
//            返回文件大小,单位字节
            long size = file.getSize();
            log.info("文件大小：{}",size);
            try {
                String bucketName = minioConfig.getBucketName();
                minioClientUtils.putObject(bucketName,file,minioFileName);
                String fileUrl = minioClientUtils.getObjectUrl(bucketName, minioFileName);
                MinioFile minioFile = new MinioFile();
                minioFile.setOriginalFileName(originalFilename);
                minioFile.setFileExtName(extName);
                minioFile.setFileName(minioFileName);
                minioFile.setFileSize(size);
                minioFile.setMime(contentType);
                minioFile.setIsDelete(0);
                minioFile.setFileUrl(fileUrl.split("\\?")[0]);
                int insert = minioFileMapper.insert(minioFile);
                if (insert > 0) {
                    MinioResponseDTO minioResponseDTO = new MinioResponseDTO();
                    minioResponseDTO.setFileId(minioFile.getId());
                    minioResponseDTO.setOriginalFileName(originalFilename);
                    minioResponseDTO.setFileUrl(minioFile.getFileUrl());
                    minioResponseDTO.setFileSize(size);
                    responseDTOList.add(minioResponseDTO);
                }
            } catch (Exception e) {
                log.error("上传文件出错:{}",e);
                return Result.fail("上传文件出错");
            }
        }

        return Result.ok(responseDTOList);
    }

    @GetMapping("/download")
    @ApiOperation(value = "测试minio文件下载")
    public Result downloadObject(HttpServletResponse response){

        minioClientUtils.downloadFile(minioConfig.getBucketName(),"1681266145326649035301417.jpg","3388.jpg",response);
        return Result.ok("下载成功");
    }

    @PostMapping("/delBatchFile")
    @ApiOperation(value = "删除minio文件下载")
    public Result delBatchFile(String key){
        try {
            minioClientUtils.removeObject(minioConfig.getBucketName(),key);
            return Result.ok("删除成功");
        } catch (Exception e) {
            return Result.fail(e);
        }
    }

    /**
     * 仅仅用于测试，是否可以正常上传文件
     */
    @GetMapping("/test")
    @ApiOperation(value = "测试minio文件上传")
    public Result testPutObject() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("D:\\3388.jpg");
        boolean bs = minioClientUtils.putObject("fsp-dev", "3388.jpg", fileInputStream, "image/jpg");
        log.info("上传成功?"+bs);
        return Result.ok("上传成功");
    }

}
